package com.bruce.tool.search.solr.domain;

import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.solr.client.solrj.SolrQuery;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 功能 :
 *
 * @author : Bruce(刘正航) 下午3:05 2018/5/8
 */
@Getter
@NoArgsConstructor(staticName = "build")
public class PageQuery implements Serializable{
    private Integer page;
    private Integer size;
    @Getter
    private List<Sort> sorts = new ArrayList<>();

    public PageQuery set(Integer page,Integer size){
        this.page = page;
        this.size = size;
        return this;
    }

    public PageQuery setSort(String field,String order){
        if(StringUtils.isBlank(field) ){
            return this;
        }
        Sort sort = new Sort();
        sort.setField(field);
        setOrder(sort, order);
        sorts.clear();
        sorts.add(sort);
        return this;
    }

    public PageQuery addSort(String field,String order){
        if(StringUtils.isBlank(field) ){
            return this;
        }
        Sort sort = new Sort();
        sort.setField(field);
        setOrder(sort, order);
        sorts.add(sort);
        return this;
    }

    private void setOrder(Sort sort, String order) {
        if( SolrQuery.ORDER.asc.name().equals(order) ){
            sort.setOrder(SolrQuery.ORDER.asc);
        }else
        if( SolrQuery.ORDER.desc.name().equals(order) ){
            sort.setOrder(SolrQuery.ORDER.desc);
        }else{
            sort.setOrder(SolrQuery.ORDER.asc);
        }
    }

    @Data
    public class Sort implements Serializable{
        private String field;
        private SolrQuery.ORDER order;
    }
}
